package zhihuilan.controlle.wechatMini;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import zhihuilan.common.WxMiniResponse;
import zhihuilan.common.enums.ResultEnum;
import zhihuilan.controlle.BasicController;
import zhihuilan.dto.*;
import zhihuilan.entity.MyCircleDiscuss;
import zhihuilan.entity.MyStaff;
import zhihuilan.entity.MyStaffMsg;
import zhihuilan.entity.MyStaffMsgRoom;
import zhihuilan.params.query.MyStaffMsgQueryParam;
import zhihuilan.params.query.MyStaffMsgRoomQueryParam;
import zhihuilan.service.MyCircleDiscussService;
import zhihuilan.service.MyStaffMsgRoomService;
import zhihuilan.service.MyStaffMsgService;
import zhihuilan.service.MyStaffService;

import javax.annotation.Resource;

import java.net.UnknownHostException;
import java.util.*;
import java.util.stream.Collectors;

import static zhihuilan.common.utils.ToolsUtils.randomStr;
import static zhihuilan.common.utils.ToolsUtils.verifymsg;

@Slf4j
@RestController
@RequestMapping("/app/Sendmsg")
public class SendmsgController extends BasicController {

    @Resource
    private WxMaService wxMaService;

    @Autowired
    private MyStaffMsgService myStaffMsgService;

    @Autowired
    private MyStaffMsgRoomService myStaffMsgRoomService;

    @Autowired
    private MyCircleDiscussService myCircleDiscussService;

    @Autowired
    private MyStaffService myStaffService;

    /**
     * @api  /Sendmsg/setSendmsg 聊天
     * @apiParam {string}  guid 用户guid
     * @apiParam {string}  msgType 消息类别
     * @apiParam {string}  content 内容
     * @apiParam {string}  sound 语音地址
     * @apiParam {string}  imgurl 图片地址
     * @apiParam {Int}  recipient 收信息人id
     * @apiParam {string}  remark 备注
     * @apiParam {string}  roomId 房间id
     * @apiParam {Int}  sender 发送人id
     * @apiParam {Int}  shopid 市场id
     * @apiParam {Int}  factoryid 厂家id
     */
    @PostMapping("/setSendmsg")
    public WxMiniResponse setSendmsg(@RequestBody MyStaffMsgQueryParam myStaffMsg) throws UnknownHostException, WxErrorException {

        if (!isCheckLogin(myStaffMsg.getGuid())) {
            //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
            return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }
       String result =  verifymsg(myStaffMsg.getContent(), currentStaff.getOpenid(),wxMaService);
        if(JSONObject.parseObject(result).getJSONObject("result").getString("suggest").equals("risky") ){
            return WxMiniResponse.error(ResultEnum.ERROR.getKey(),"请文明言论");
        }
        myStaffMsg.setStatus(0);
        myStaffMsg.setCreateTime(new Date().getTime()/1000);
        myStaffMsg.setCreateUser(currentStaff.getId());
        myStaffMsg.setStaffId(currentStaff.getId());
        Integer i =  myStaffMsgService.addEntity(myStaffMsg);
        myStaffMsg.setStatus(1);
        myStaffMsg.setCreateUser(myStaffMsg.getRecipient());
        myStaffMsg.setStaffId(myStaffMsg.getRecipient());
        Integer j = myStaffMsgService.addEntity(myStaffMsg);
        MyStaffMsgRoomQueryParam myStaffMsgRoom = new MyStaffMsgRoomQueryParam();
        myStaffMsgRoom.setRoomId(myStaffMsg.getRoomId());
        myStaffMsgRoom.setRecipient(myStaffMsg.getRecipient());
        myStaffMsgRoom.setStaffId(myStaffMsg.getRecipient());
        MyStaffMsgRoom staffMsgRoom = myStaffMsgRoomService.selectMyStaffMsgRoom(myStaffMsgRoom);
        if(staffMsgRoom==null){
            MyStaffMsgRoomQueryParam msgRoom = new MyStaffMsgRoomQueryParam();
            msgRoom.setRoomId(myStaffMsg.getRoomId());
            msgRoom.setSender(myStaffMsg.getSender());
            msgRoom.setRecipient(myStaffMsg.getRecipient());
            msgRoom.setCreateTime(new Date().getTime()/1000);
            msgRoom.setCreateUser(myStaffMsg.getRecipient());
            msgRoom.setStaffId(myStaffMsg.getRecipient());
            msgRoom.setTopStatus(0);
            msgRoom.setDeleteStatus(0);
            myStaffMsgRoomService.addEntity(msgRoom);
        }
        myStaffMsgRoom = new MyStaffMsgRoomQueryParam();
        myStaffMsgRoom.setRoomId(myStaffMsg.getRoomId());
        myStaffMsgRoom.setUpdateUser(currentStaff.getId());
        myStaffMsgRoom.setUpdateTime(new Date().getTime()/1000);
        myStaffMsgRoom.setDeleteStatus(0);
        myStaffMsgRoomService.updateEntity(myStaffMsgRoom);
        if(i>0&&j>0){
            return WxMiniResponse.ok("发送成功");
        }
        return WxMiniResponse.error(ResultEnum.ERROR.getKey(),"发送失败");
   }

    /**
     * @api /Sendmsg/getSendmsg 获取聊天记录
     * @apiParam {string}  guid 用户guid
     * @apiParam {Int}  page 页数
     *  @apiParam {Int}  time 时间
     * @apiParam {string}  roomId 房间id
     * @apiParam {Int}  pagesize 每页的数据量
     */
    @PostMapping("/getSendMsg")
    public WxMiniResponse getSendmsg(@RequestBody MyStaffMsgQueryParam myStaffMsg){
        if (!isCheckLogin(myStaffMsg.getGuid())) {
            //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
            return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }
        MyStaffMsgRoomQueryParam myStaffMsgRoom = new MyStaffMsgRoomQueryParam();
        myStaffMsgRoom.setRoomId(myStaffMsg.getRoomId());
        myStaffMsgRoom.setStaffId(currentStaff.getId());
        MyStaffMsgRoom msgRoom = myStaffMsgRoomService.selectMyStaffMsgRoom(myStaffMsgRoom);
        if(msgRoom==null){
            return  WxMiniResponse.error(ResultEnum.ERROR.getKey(),"聊天室不存在");
        }
        if(msgRoom.getSender().equals(currentStaff.getId())||msgRoom.getRecipient().equals(currentStaff.getId())){
            MyStaffMsgRoom staffMsgRoom = new MyStaffMsgRoom();
            MyStaffMsgQueryParam staffMsg = new MyStaffMsgQueryParam();
            staffMsg.setStaffId(currentStaff.getId());
            staffMsg.setRoomId(myStaffMsg.getRoomId());
            myStaffMsgService.updateEntity(staffMsg);
            staffMsgRoom.setStaffId(currentStaff.getId());
            staffMsgRoom.setRoomId(myStaffMsg.getRoomId());
            staffMsgRoom.setCreateTime(myStaffMsg.getTime());
            myStaffMsg.setStaffId(currentStaff.getId());
            PageDto<MyStaffMsg> staffMsgPage = myStaffMsgService.selectMyStaffMsgList(myStaffMsg);

            List<MyStaffMsgDto> convertList = staffMsgPage.getRecords().stream().map(po -> {
                MyStaffMsgDto myStaffMsgDto = new MyStaffMsgDto();
                BeanUtils.copyProperties(po, myStaffMsgDto);
                return myStaffMsgDto;
            }).collect(Collectors.toList());
            WxMiniPageDto<MyStaffMsgDto> resultPage = new WxMiniPageDto<>(staffMsgPage.getCurrent(), staffMsgPage.getSize());// 第1页，每页10条数据
            BeanUtils.copyProperties(staffMsgPage, resultPage);
            resultPage.setData(convertList);
            return WxMiniResponse.ok(resultPage);
        }
        return WxMiniResponse.ok();
    }

    /**
     * @api   Sendmsg/setRead 退出房间标识已读
     * @apiParam {string}  guid 用户guid
     * @apiParam {string}  roomId 房间id
     */
    @PostMapping("/setRead")
    public WxMiniResponse setRead(@RequestBody MyStaffMsgQueryParam myStaffMsgQueryParam){
        if (!isCheckLogin(myStaffMsgQueryParam.getGuid())) {
            //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
            return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }
        myStaffMsgQueryParam.setStaffId(currentStaff.getId());
        myStaffMsgService.updateReadEntity(myStaffMsgQueryParam);
        return WxMiniResponse.ok();
    }

    /**
     * @api  Sendmsg/getMsgRedCount 获取聊天红点
     * @apiParam {string}  guid 用户guid
     */
    @PostMapping("/getMsgRedCount")
    public WxMiniResponse getMsgRedCount(@RequestBody MyStaffMsgQueryParam myStaffMsgQueryParam){
        if (!isCheckLogin(myStaffMsgQueryParam.getGuid())) {
            //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
//            return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
            return WxMiniResponse.ok();
        }
        myStaffMsgQueryParam.setStaffId(currentStaff.getId());
        Map map = new HashMap();
        Long countRedMsg = myStaffMsgService.getRedCountMsg(myStaffMsgQueryParam);
        MyCircleDiscuss myCircleDiscuss = new MyCircleDiscuss();
        myCircleDiscuss.setParentid(0);
        myCircleDiscuss.setPstaffid(currentStaff.getId());
        Integer countDiscuss = myCircleDiscussService.countRedDiscuss(myCircleDiscuss);
        MyCircleDiscuss myCircleDiscuss1 = myCircleDiscussService.getMyCircleDiscussOne(myCircleDiscuss);
        MyCircleDiscussDto myCircleDiscussDto = new MyCircleDiscussDto();
        if(myCircleDiscuss1!=null){
            BeanUtils.copyProperties(myCircleDiscuss1,myCircleDiscussDto);
            map.put("discuss_lastone",myCircleDiscussDto);
        }
        map.put("sendmsg",countRedMsg);
        map.put("discuss",countDiscuss);
        return WxMiniResponse.ok(map);
    }

    /**
     * @api  /Sendmsg/getRooms 获取聊天房间
     * @apiParam {string}  guid 用户guid
     * @apiParam {Int}  recipient 收信息人id
     */
    @PostMapping("/getRooms")
    public WxMiniResponse getRooms(@RequestBody MyStaffMsgRoomQueryParam myStaffMsgRoomQueryParam){
        if (!isCheckLogin(myStaffMsgRoomQueryParam.getGuid())) {
            //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
            return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }
        if(myStaffMsgRoomQueryParam.getRecipient()==currentStaff.getId()){
            return WxMiniResponse.error(ResultEnum.ERROR.getKey(),"自己不能聊天！");
        }
        MyStaff mystaff =myStaffService.selectMyStaffById(myStaffMsgRoomQueryParam.getRecipient());
        if(mystaff==null){
            return  WxMiniResponse.error(ResultEnum.ERROR.getKey(),"聊天对象有异常");
        }
        myStaffMsgRoomQueryParam.setStaffId(currentStaff.getId());
        MyStaffMsgRoom myStaffMsgRoom = myStaffMsgRoomService.selectMyStaffMsgRoom(myStaffMsgRoomQueryParam);

        if(myStaffMsgRoom==null){
            MyStaffMsgRoomQueryParam staffMsgRoom = new MyStaffMsgRoomQueryParam();
            String roomId = new Date().getTime()/1000+randomStr(4);
            staffMsgRoom.setRoomId(roomId);
            staffMsgRoom.setSender(currentStaff.getId());
            staffMsgRoom.setRecipient(myStaffMsgRoomQueryParam.getRecipient());
            staffMsgRoom.setCreateTime(new Date().getTime()/1000);
            staffMsgRoom.setCreateUser(currentStaff.getId());
            staffMsgRoom.setStaffId(currentStaff.getId());
            staffMsgRoom.setDeleteStatus(0);
            staffMsgRoom.setTopStatus(0);
            myStaffMsgRoomService.addEntity(staffMsgRoom);
            MyStaffMsgRoomDto myStaffMsgRoomDto = new MyStaffMsgRoomDto();
            BeanUtils.copyProperties(staffMsgRoom,myStaffMsgRoomDto);
            if(mystaff!=null&&mystaff.getId()>0){
                myStaffMsgRoomDto.setRecipientGuid(mystaff.getGuid());
                myStaffMsgRoomDto.setRecipientUserreal(mystaff.getUserreal());
                myStaffMsgRoomDto.setRecipientAvatar(mystaff.getHeadimgurl());
                myStaffMsgRoomDto.setRecipientTelephone(mystaff.getTelephone());
                myStaffMsgRoomDto.setRecipientTitle(mystaff.getTitle());
                myStaffMsgRoomDto.setRecipientLogo(mystaff.getLogo());
            }
            return WxMiniResponse.ok(myStaffMsgRoomDto);
        }
         myStaffMsgRoomService.updateDeleteStatus(myStaffMsgRoomQueryParam);
        MyStaffMsgRoomDto myStaffMsgRoomDto = new MyStaffMsgRoomDto();
        BeanUtils.copyProperties(myStaffMsgRoom,myStaffMsgRoomDto);
        if(mystaff!=null&&mystaff.getId()>0){
            myStaffMsgRoomDto.setRecipientGuid(mystaff.getGuid());
            myStaffMsgRoomDto.setRecipientUserreal(mystaff.getUserreal());
            myStaffMsgRoomDto.setRecipientAvatar(mystaff.getHeadimgurl());
            myStaffMsgRoomDto.setRecipientTelephone(mystaff.getTelephone());
            myStaffMsgRoomDto.setRecipientTitle(mystaff.getTitle());
            myStaffMsgRoomDto.setRecipientLogo(mystaff.getLogo());
        }
        return WxMiniResponse.ok(myStaffMsgRoomDto);
    }

    /**
     * @api /Sendmsg/getRoomsList 获取房间列表
     * @apiParam {string}  guid 用户guid
     * @apiParam {Int}  page 页数
     * @apiParam {Int}  pagesize 每页的数据量
     */
    @PostMapping("/getRoomsList")
    public WxMiniResponse getRoomsList(@RequestBody MyStaffMsgRoomQueryParam myStaffMsgRoomQueryParam){
        if (!isCheckLogin(myStaffMsgRoomQueryParam.getGuid())) {
            //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
//            return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
            return WxMiniResponse.ok();
        }
        myStaffMsgRoomQueryParam.setStaffId(currentStaff.getId());
        Page<MyStaffMsgRoom> staffMsgRoomPage = myStaffMsgRoomService.selectMyStaffMsgRoomList(myStaffMsgRoomQueryParam);
        List<MyStaffMsgRoomDto> convertList = staffMsgRoomPage.getRecords().stream().map(po -> {
            Integer id = po.getSender();
            if(id.equals(currentStaff.getId())){
                id = po.getRecipient();
            }
            MyStaff myStaff = myStaffService.selectMyStaffById(id);
            MyStaffMsgQueryParam myStaffMsgQueryParam = new MyStaffMsgQueryParam();
            myStaffMsgQueryParam.setStaffId(currentStaff.getId());
            myStaffMsgQueryParam.setRecipient(currentStaff.getId());
            myStaffMsgQueryParam.setSender(id);
            Long read = myStaffMsgService.getRedCountMsg(myStaffMsgQueryParam);
            myStaffMsgQueryParam = new MyStaffMsgQueryParam();
            myStaffMsgQueryParam.setStaffId(currentStaff.getId());
            myStaffMsgQueryParam.setRecipient(id);
            myStaffMsgQueryParam.setSender(id);
            MyStaffMsg myStaffMsg = myStaffMsgService.selectMyStaffMsg(myStaffMsgQueryParam);
            MyStaffMsgDto myStaffMsgDto = new MyStaffMsgDto();
            if(myStaffMsg!=null){
                BeanUtils.copyProperties(myStaffMsg,myStaffMsgDto);
            }
            MyStaffMsgRoomDto myStaffMsgRoomDto = new MyStaffMsgRoomDto();
            BeanUtils.copyProperties(po, myStaffMsgRoomDto);
//            myStaffMsgRoomDto.setDeleteStatus(po.getDeleteStatus());
//            myStaffMsgRoomDto.setRoomId(po.getRoomId());
//            myStaffMsgRoomDto.setUpdateTime(po.getUpdateTime());
//            myStaffMsgRoomDto.setUpdateUser(po.getUpdateUser());
//            myStaffMsgRoomDto.setCreateTime(po.getCreateTime());
//            myStaffMsgRoomDto.setCreateUser(po.getCreateUser());
//            myStaffMsgRoomDto.setSender(po.getSender());
//            myStaffMsgRoomDto.setStaffId(po.getStaffId());
//            myStaffMsgRoomDto.setRecipient(po.getRecipient());
//            myStaffMsgRoomDto.setTopStatus(po.getTopStatus());
//            myStaffMsgRoomDto.setId(po.getId());
            myStaffMsgRoomDto.setRecipientGuid(myStaff.getGuid());
            myStaffMsgRoomDto.setRecipientUserreal(myStaff.getUserreal());
            myStaffMsgRoomDto.setRecipientAvatar(myStaff.getHeadimgurl());
            myStaffMsgRoomDto.setRecipientTelephone(myStaff.getTelephone());
            myStaffMsgRoomDto.setRecipientTitle(myStaff.getTitle());
            myStaffMsgRoomDto.setRecipientLogo(myStaff.getLogo());
            myStaffMsgRoomDto.setRead(read.intValue());
            myStaffMsgRoomDto.setLastone(myStaffMsgDto);
            return myStaffMsgRoomDto;
        }).collect(Collectors.toList());
        WxMiniPageDto<MyStaffMsgRoomDto> resultPage = new WxMiniPageDto<>(staffMsgRoomPage.getCurrent(), staffMsgRoomPage.getSize());// 第1页，每页10条数据
        BeanUtils.copyProperties(staffMsgRoomPage, resultPage);
        resultPage.setData(convertList);
        return WxMiniResponse.ok(resultPage);
    }

    /**
     * @api /Sendmsg/setRoomDeleteStatus 删除聊天
     * @apiParam {string}  guid 用户guid
     * @apiParam {String}  roomId 房间号
     */
    @PostMapping("/setRoomDeleteStatus")
    public WxMiniResponse setRoomDeleteStatus(@RequestBody MyStaffMsgRoomQueryParam myStaffMsgRoomQueryParam){
        if (!isCheckLogin(myStaffMsgRoomQueryParam.getGuid())) {
            //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
            return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }
        myStaffMsgRoomQueryParam.setStaffId(currentStaff.getId());
        MyStaffMsgRoom msgRoom = myStaffMsgRoomService.selectMyStaffMsgRoom(myStaffMsgRoomQueryParam);
        if(msgRoom==null){
            return WxMiniResponse.error(ResultEnum.ERROR.getKey(),"操作失败！");
        }
        Integer i =  myStaffMsgRoomService.updateDelete(myStaffMsgRoomQueryParam);
        MyStaffMsgQueryParam myStaffMsg = new MyStaffMsgQueryParam();
        myStaffMsg.setRoomId(myStaffMsgRoomQueryParam.getRoomId());
        myStaffMsg.setStaffId(currentStaff.getId());
        myStaffMsgService.delMyStaffMsg(myStaffMsg);
        if(i>0){
            return WxMiniResponse.ok(i);
        }
        return WxMiniResponse.error(ResultEnum.ERROR.getKey(),"操作失败！");

    }

    /**
     * @api /Sendmsg/setRoomTopStatus 置顶聊天
     * @apiParam {string}  guid 用户guid
     * @apiParam {String}  roomId 房间号
     */
    @PostMapping("/setRoomTopStatus")
    public WxMiniResponse setRoomTopStatus(@RequestBody MyStaffMsgRoomQueryParam myStaffMsgRoomQueryParam){
        if (!isCheckLogin(myStaffMsgRoomQueryParam.getGuid())) {
            //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
            return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }
        myStaffMsgRoomQueryParam.setStaffId(currentStaff.getId());
        MyStaffMsgRoom msgRoom = myStaffMsgRoomService.selectMyStaffMsgRoom(myStaffMsgRoomQueryParam);
        if(msgRoom==null){
            return WxMiniResponse.error(ResultEnum.ERROR.getKey(),"操作失败！");
        }
        if(msgRoom.getTopStatus()==1){
            myStaffMsgRoomQueryParam.setTopStatus(0);
        }else{
            myStaffMsgRoomQueryParam.setTopStatus(1);
        }
        Integer i =  myStaffMsgRoomService.updateTopStatus(myStaffMsgRoomQueryParam);
        if(i>0){
            return WxMiniResponse.ok(i);
        }
        return WxMiniResponse.error(ResultEnum.ERROR.getKey(),"操作失败！");
    }

}
